﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class FormBase : Form
    {
        /// <summary>
        /// 绑定的html文件名
        /// </summary>
        public string HtmlFile
        {
            get => htmlFile;
            set
            {
                htmlFile = value;
                if ((webView != null) && (webView.CoreWebView2 != null))
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory;
                    webView.CoreWebView2.Navigate($"file:///{path}assets/{htmlFile}");
                }
            }
        }
        private string htmlFile;
        /// <summary>
        /// 寄宿到js脚本中的C#对象，可以在js代码中调用该对象
        /// </summary>
        public Dictionary<string, object> HostScriptObjects { get; set; } = new Dictionary<string, object>();

        public FormBase()
        {
            InitializeComponent();
            Load += Form_Load;
            webView.KeyDown += Form_KeyDown;
            MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
        }

        private void Form_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.F12 && webView.CoreWebView2 != null)
                //开启开发者工具
                webView.CoreWebView2.OpenDevToolsWindow();
        }

        private async void Form_Load(object sender, EventArgs e)
        {
            //寄宿winform对象到js中，以便调用winform的一些方法(最小化，最大化等)
            HostScriptObjects.Add("winform", new FormBaseScriptCallback(this));

            webView.CoreWebView2InitializationCompleted += WebViewInitializationCompleted;
            await webView.EnsureCoreWebView2Async(null);

            if ((webView != null) && (webView.CoreWebView2 != null))
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                webView.CoreWebView2.Navigate($"file:///{path}assets/{htmlFile}");
            }
        }

        private void WebViewInitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            //禁止dev菜单
            webView.CoreWebView2.Settings.AreDevToolsEnabled = false;
            //禁止所有菜单
            webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;

            //向绑定的web页注入C#对象
            if (HostScriptObjects == null || HostScriptObjects.Count == 0) return;
            foreach (var item in HostScriptObjects)
            {
                RegistScriptObject(item.Key, item.Value);
            }
        }

        public void RegistScriptObject(string keyName, object rowObject)
        {
            if ((webView != null) && (webView.CoreWebView2 != null))
            {
                if (!HostScriptObjects.ContainsKey(keyName)) HostScriptObjects.Add(keyName,rowObject);
                //注册C#的对象，以在js脚本中调用
                webView.CoreWebView2.AddHostObjectToScript(keyName, rowObject);
                string script = $"var winform = chrome.webview.hostObjects.{keyName}";
                webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
            }
        }

        /// <summary>
        /// 调用js中的定义的函数，函数只有一个参数对象
        /// </summary>
        /// <param name="funcName">函数名称</param>
        /// <param name="param">函数参数对象</param>
        /// <returns></returns>
        public async Task<string> ExecuteScriptAsync(string funcName, object param) 
        {
            string data = JsonConvert.SerializeObject(param);
            return await webView.CoreWebView2.ExecuteScriptAsync($"{funcName}({data})");
        }
    }
}
